<?php
/*
Plugin Name: SHOUTcast Sidebar Widget
Plugin URI: http://www.wesleyevans.net/shoutcast-sidebar-widget/
Description: Adds a SHOUTcast Widget to your Wordpress Sidebar
Author: Wesley Evans
Version: 1.3.2
Author URI: http://www.wesleyevans.net

Copyright (C) 2006 Wesley Evans
*/

function widget_shoutcast_init() {

	// Check for the required plugin functions. This will prevent fatal
	// errors occurring when you deactivate the dynamic-sidebar plugin.
	if ( !function_exists('register_sidebar_widget') )
		return;

	// This is the function that outputs the SHOUTcast html
	function widget_shoutcast($args, $number = 1) {
		
		// $args is an array of strings that help widgets to conform to
		// the active theme: before_widget, before_title, after_widget,
		// and after_title are the array keys. Default tags: li and h2.
		extract($args);

		// Each widget can store its own options. We keep strings here.
		$options = get_option('widget_shoutcast');
		$title = $options[$number]['title'];
		$url = $options[$number]['url'];

		if ($title=="") {
			$title = "SHOUTcast Radio";
		}

		// Display Title
		echo $before_widget . $before_title . $title . $after_title;
		echo '<br/>';

                // We have to set our user_agent to Mozilla, otherwise SHOUTcast
		// assumes we are a media player and tries to stream
                
                ini_set("display_errors","On");
		ini_set("error_reporting",ini_get("error_reporting") & ~E_WARNING);

                if (ini_get("allow_url_fopen")=="1") {
                   ini_set("user_agent","Mozilla");
		   $file = file_get_contents($url . '/index.html');
                } else {
                   $ch = curl_init();
                   curl_setopt ($ch, CURLOPT_URL, $url . '/index.html');
                   curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
                   curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, 5);
                   curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla");
                   $file = curl_exec($ch);
                   curl_close($ch);
                }

		// Try to Find a "current status" for the server
		preg_match("/Server Status: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		$status = $matches[1];

		// If our server is running, then we lookup the song and display
		// the sc_running template
		if ($status=="Server is currently up and public." || $status=="Server is currently up and private.") {
		        preg_match("/Current Song: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		        $songname = $matches[1];
			// Stream is up at 192 kbps with <B>72 of 400 listeners (69 unique)
		        //preg_match("/Stream is up at (.*) kbps with <B>(.*) of (.*) listeners (.*) unique)/U", $file, $matches);
		        preg_match("/Stream is up at (.*) kbps with <B>(.*) of (.*) listeners \((.*) unique\)/U", $file, $matches);
		        $bitrate = $matches[1];
		        $currListeners = $matches[2];
		        $maxListeners = $matches[3];
		        $uniqueListeners = $matches[4];
		        preg_match("/Stream Genre: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		        $genre = $matches[1];
		        preg_match("/Listener Peak: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		        $peak = $matches[1];
		        preg_match("/Stream Title: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		        $streamTitle = $matches[1];
		        preg_match("/Average Listen Time: <\/font><\/td><td><font class=default><b>(.*)<\/b>/U", $file, $matches);
		        $avgTime = $matches[1];
			$template = file_get_contents("wp-content/plugins/sc_widget/sc_running.htm");
                        $template = preg_replace('/(.*)(\$songtitle)(.*)/', "\${1}$songname\${3}", $template);
                        $template = preg_replace('/(.*)(\$url)(.*)/', "\${1}$url\${3}", $template);
                        $template = preg_replace('/(.*)(\$title)(.*)/', "\${1}$title\${3}", $template);
                        $template = preg_replace('/(.*)(\$number)(.*)/', "\${1}$number\${3}", $template);
                        $template = preg_replace('/(.*)(\$bitrate)(.*)/', "\${1}$bitrate\${3}", $template);
                        $template = preg_replace('/(.*)(\$currListeners)(.*)/', "\${1}$currListeners\${3}", $template);
                        $template = preg_replace('/(.*)(\$maxListeners)(.*)/', "\${1}$maxListeners\${3}", $template);
                        $template = preg_replace('/(.*)(\$uniqueListeners)(.*)/', "\${1}$uniqueListeners\${3}", $template);
                        $template = preg_replace('/(.*)(\$genre)(.*)/', "\${1}$genre\${3}", $template);
                        $template = preg_replace('/(.*)(\$peak)(.*)/', "\${1}$peak\${3}", $template);
                        $template = preg_replace('/(.*)(\$streamTitle)(.*)/', "\${1}$streamTitle\${3}", $template);
                        $template = preg_replace('/(.*)(\$avgTime)(.*)/', "\${1}$avgTime\${3}", $template);
			echo $template;
		} else {
			echo file_get_contents("wp-content/plugins/sc_widget/sc_down.htm");
		}

		echo $after_widget;
	}

	// This is the function that outputs the form to let the users edit
	// the widget's title. It's an optional feature that users cry for.
	function widget_shoutcast_control($number) {

		// Get our options and see if we're handling a form submission.
		$options = get_option('widget_shoutcast');
		//if ( !is_array($options) )
			//$options = array('title'=>'', 'url'=>__('http://www.wesleyevans.net:8000', 'widgets'));
		if ( $_POST['shoutcast-submit-' . $number] ) {

			// Remember to sanitize and format use input appropriately.
			$options[$number]['title'] = strip_tags(stripslashes($_POST['shoutcast-title-' . $number]));
			$options[$number]['url'] = strip_tags(stripslashes($_POST['shoutcast-url-' . $number]));
			update_option('widget_shoutcast', $options);
		}

		// Be sure you format your options to be valid HTML attributes.
		$title = htmlspecialchars($options[$number]['title'], ENT_QUOTES);
		$url = htmlspecialchars($options[$number]['url'], ENT_QUOTES);
		
		// Here is our little form segment. Notice that we don't need a
		// complete form. This will be embedded into the existing form.
		echo '<p style="text-align:right;"><label for="shoutcast-title-' . $number . '">' . __('Title:', 'widgets') . ' <input style="width: 300px;" id="shoutcast-title-' . $number . '" name="shoutcast-title-' . $number . '" type="text" value="'.$title.'" /></label></p>';
		echo '<p style="text-align:right;"><label for="shoutcast-url-' . $number . '">' . __('URL:', 'widgets') . ' <input style="width: 300px;" id="shoutcast-url-' . $number . '" name="shoutcast-url-' . $number . '" type="text" value="'.$url.'" /></label></p>';
		echo '<input type="hidden" id="shoutcast-submit-' . $number . '" name="shoutcast-submit-' . $number . '" value="1" />';
	}
	
       function widget_shoutcast_setup() {
                $options = $newoptions = get_option('widget_shoutcast');
                if ( isset($_POST['shoutcast-number-submit']) ) {
                        $number = (int) $_POST['shoutcast-number'];
                        if ( $number > 9 ) $number = 9;
                        if ( $number < 1 ) $number = 1;
                        $newoptions['number'] = $number;
                }
                if ( $options != $newoptions ) {
                        $options = $newoptions;
                        update_option('widget_shoutcast', $options);
                        widget_shoutcast_register($options['number']);
                }
        }

        function widget_shoutcast_page() {
                $options = $newoptions = get_option('widget_shoutcast');
        ?>
                <div class="wrap">
                        <form method="POST">
                                <h2>SHOUTcast Widgets</h2>
                                <p style="line-height: 30px;"><?php _e('How many SHOUTcast widgets would you like?'); ?>
                                <select id="shoutcast-number" name="shoutcast-number" value="<?php echo $options['number']; ?>">
        <?php for ( $i = 1; $i < 10; ++$i ) echo "<option value='$i' ".($options['number']==$i ? "selected='selected'" : '').">$i</option>"; ?>
                                </select>
                                <span class="submit"><input type="submit" name="shoutcast-number-submit" id="shoutcast-number-submit" value="<?php _e('Save'); ?>" /></span></p>
                        </form>
                </div>
        <?php
        }


        function widget_shoutcast_register() {
                $options = get_option('widget_shoutcast');
                $number = $options['number'];
                if ( $number < 1 ) $number = 1;
                if ( $number > 9 ) $number = 9;
                for ($i = 1; $i <= 9; $i++) {
                        $name = array('SHOUTcast %s', null, $i);
                        register_sidebar_widget($name, $i <= $number ? 'widget_shoutcast' : /* unregister */ '', $i);
                        register_widget_control($name, $i <= $number ? 'widget_shoutcast_control' : /* unregister */ '', 350, 100, $i);
                }
                add_action('sidebar_admin_setup', 'widget_shoutcast_setup');
                add_action('sidebar_admin_page', 'widget_shoutcast_page');
        }
        // Delay plugin execution to ensure Dynamic Sidebar has a chance to load first
        widget_shoutcast_register();

}

// Run our code later in case this loads prior to any required plugins.
add_action('widgets_init', 'widget_shoutcast_init');

?>
